﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.Text.RegularExpressions;

namespace Hands.UriRewrite
{
    internal static class ConfigFileReader
    {
        private const string CONFIG_FILE_NAME = "Valkyrja.xml";

        private const string REWRITE_NODE_NAME = "rewrite";

        private const int RAW = 0;
        private const int REWRITE_TO = 1;

        static ConfigFileReader()
        {
            readConfig();
        }

        internal static void readConfigFile()
        { }

        private static void readConfig()
        {
            //设置配置文件的读取路径为网站项目的根目录
            StringBuilder configFilePath = new StringBuilder();
            //configFilePath.Append(HttpRuntime.AppDomainAppPath.ToString());
            configFilePath.Append(AppDomain.CurrentDomain.BaseDirectory);
            configFilePath.Append(CONFIG_FILE_NAME);

            XmlDocument xml = new XmlDocument();
            xml.Load(configFilePath.ToString());

            //读取rewrite节点配置信息
            XmlNodeList rewriteNodes = xml.GetElementsByTagName(REWRITE_NODE_NAME);

            StringBuilder rootPathRegex = new StringBuilder();

            foreach (XmlNode rewriteNode in rewriteNodes)
            {
                string rootPath = rewriteNode.ChildNodes[0].InnerText;
                UriRootPath uri = new UriRootPath(rootPath);
                createRegex(rootPath, ref rootPathRegex);

                StringBuilder branchRegex = new StringBuilder();
                for (int i = 1; i < rewriteNode.ChildNodes.Count; i++)
                {
                    XmlNode node = rewriteNode.ChildNodes[i];

                    Match branch = RegularExpressionsRule.PARSING_CONFIG_URI_BRANCH_REGEX.Match(node.ChildNodes[RAW].InnerText);

                    createRegex(branch.Value, ref branchRegex);

                    UriBranchPath uriBranch = new UriBranchPath(branch.Value, new StringBuilder(node.ChildNodes[REWRITE_TO].InnerText));
                    uriBranch.parsingParaName(node.ChildNodes[RAW].InnerText);

                    uri.addUriBranch(branch.Value, uriBranch);
                }
                uri.addBranchPathRegex(new Regex(branchRegex.ToString(), RegexOptions.Compiled));
                ConfigStorage.add(rootPath, uri);
            }
            UriRootPathQuery.initRootPathRegex(rootPathRegex.ToString());
        }


        private static void createRegex(string rootPath, ref StringBuilder path)
        {
            if (path.Length != 0)
            {
                path.Append("|");
                path.Append(rootPath);
            }
            else
            {
                path.Append(rootPath);
            }
        }
    }
}
